package cn.springmvc.noconfig.initializer;

import cn.springmvc.noconfig.config.MvcConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

/**
 * ClassName: WebInitializer
 * Desc: 初始化类，代替 web.xml配置,可以使用继承 AbstractAnnotationConfigDispatcherServletInitializer 优化
 * 如 AbstractDispatcherServletInitializer 类中就添加了 dispatcher 的 servlet
 * http://www.blogjava.net/yongboy/archive/2010/12/30/346209.html
 * http://sishuok.com/forum/blogPost/list/7981.html
 * <p>
 * <p>
 * {@link ServletContainerInitializer}
 * Date： 2017/5/3
 * Created：shaom
 */
@Deprecated
public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        /*AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(MvcConfig.class);
        ctx.setServletContext(servletContext);

        // 添加 Spring Listener
        servletContext.addListener(new ContextLoaderListener(ctx));

        // 添加 CharacterEncodingFilter
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("utf-8");
        FilterRegistration.Dynamic registration = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
        registration.setAsyncSupported(isAsyncSupported());
        registration.addMappingForUrlPatterns(getDispatcherTypes(), false, "*//*");

        // 配置spring mvc,这边可以配置servlet的配置
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.setAsyncSupported(true);
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);*/

        ServletRegistration.Dynamic registration = servletContext.addServlet("example", new DispatcherServlet());
        registration.setLoadOnStartup(1);
        registration.addMapping("/example/*");

    }

    private boolean isAsyncSupported() {
        return true;
    }

    private EnumSet<DispatcherType> getDispatcherTypes() {
        return isAsyncSupported() ?
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC) :
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE);
    }
}
